<template>
  <!-- 上传厂家证照的表格modal -->
  <div>
    <basic-modal 
        :modalOpt="modal" 
        :buttonText="['确认结算','关闭']"
        :loadings="btnLoading" 
        @onMakeSure="onPush"
        @closeModal="closeModal"
        :footer="footer" 
    >
      <template #cusBtn>
      </template>
      <template>
        <batch-operat-btn v-if="editable" :isView="false" 
            :addData="false" @onAddData="onAddData"
            :delectData="true" @onDelectData="onDelectData"
            :optData="optText" @onOptData="onBatchAudit">
          <template #cusBtn> </template>
        </batch-operat-btn>
        <!-- <a-list-info :infoDatas="infoDatas" /> -->
        <div class="recordBox">
          <a-list-table
            :columns="columns"
            :tableData="listdata"
            :isSelecttion="true"
            :loading="loading"
            :scroll="{ y: null }"
            :pagination="pagination"
            @onAction="onAction"
            @onselectChange="onselectChange"
            @onTableChange="handleTableChange"
          >
          </a-list-table>
        </div>
      </template>
    </basic-modal>
    <viewModal ref="viewModal" @ok="handleModalSaveOk" @close="handleModalCancel" />
    <auditModal ref="auditModal" @ok="handleModalSaveOk" @close="handleModalCancel" />
  </div>
</template>

<script>
import basicModal from '@/views/app/biz/common/basicModal'
import aListTable from '@/views/app/biz/common/aListTable'
import aListInfo from '@/views/app/biz/common/aListInfo'
import batchOperatBtn from '@/views/app/biz/common/batchOperatBtn'
import viewModal from '../settlementInvoice/viewModal'
import auditModal from '../settlementInvoice/auditModal'

import {
  getInfoByPid,
  getByConditions,
  getByConditionsCount,
} from '../settlementInvoice/invoice'
import {
  saveInfo
} from './settlement'
export default {
  components: {
    basicModal,
    aListTable,
    batchOperatBtn,
    aListInfo,
    viewModal,
    auditModal
  },
  data() {
    return {
      footer:undefined,
      editable:false,
      loading: false,
      btnLoading:false,
      modal: {
        modalVisible: false,
        modalTitle: '审核证照',
        modalWidth: '80vw',
        maxHeight:'70vh'
      },
      infoDatas:[
          { title: '销售单号', id: 'saleOrderNo', value: ''},
          { title: '采购类型', id: 'saletype', value: ''},
          { title: '客户名称', id: 'customerName', value: '' },
          { title: '含税总价(元)', id: 'totalPrice', value: '',style:'fontWeight:bolder',toFixed2:true  },
          { title: '送货类型', id: 'deliveryType', value: '' },
          { title: '应收金额(元)', id: 'receivableAmount', value: '' },
          { title: '税费(元)', id: 'taxes', value: '' },
          { title: '已收金额(元)', id: '	paidAmount', value: '' },
          { title: '配送状态', id: 'deliveryState', value: '' },
          { title: '开票状态', id: 'invoiceState', value: '' },
          { title: '订单状态', id: 'saleOrderState', value: '' },
          { title: '销售单生成时间', id: 'saleOrderCreateTime', value: '' },
          { title: '销售单确认时间', id: 'saleOrderCfmTime', value: '' },
          { title: '销售单完成时间', id: 'saleOrderFinTime', value: '' },
          { title: '采购单位备注', id: 'remarks', value: '' },
      ],
      columns:[
        { title: '结算单号', dataIndex: 'settlementNo', key: 'settlementNo', align: 'center' },
        { title: '买方单位', dataIndex: 'customerName', key: 'customerName', align: 'center' },
        { title: '关联销售订单', dataIndex: 'saleOrderNo', key: 'saleOrderNo', align: 'center' },
        // { title: '买方税号', dataIndex: 'customerTaxNo', key: 'customerTaxNo', align: 'center' },
        // { title: '买方地址电话', dataIndex: 'customerAddrTell', key: 'customerAddrTell', align: 'center' },
        // { title: '买方银行账号', dataIndex: 'customerAccountNum', key: 'customerAccountNum', align: 'center' },
        { title: '开具单位', dataIndex: 'supplierOrgName', key: 'supplierOrgName', align: 'center' },
        // { title: '开具单位税号', dataIndex: 'supplierTaxNo', key: 'supplierTaxNo', align: 'center' },
        // { title: '开具单位地址电话', dataIndex: 'supplierAddrTel', key: 'supplierAddrTel', align: 'center' },
        // { title: '开具单位银行账号', dataIndex: 'supplierAccountNum', key: 'supplierAccountNum', align: 'center' },
        { title: '发票种类', dataIndex: 'invoiceType', key: 'invoiceType', align: 'center' },
        { title: '发票号码', dataIndex: 'invoiceNo', key: 'invoiceNo', align: 'center' },
        { title: '发票代码', dataIndex: 'invoiceCode', key: 'invoiceCode', align: 'center' },
        // { title: '红票标志', dataIndex: 'redFlag', key: 'redFlag', align: 'center' },
        { title: '无税总价', dataIndex: 'totalIunitprice', key: 'totalIunitprice', align: 'center' ,scopedSlots: { customRender: 'tofixed2' } },
        { title: '含税总价', dataIndex: 'totalPrice', key: 'totalPrice', align: 'center',scopedSlots: { customRender: 'tofixed2' }  },
        { title: '税率', dataIndex: 'tax', key: 'tax', align: 'center', scopedSlots: { customRender: 'percentage' } },
        { title: '税额', dataIndex: 'taxes', key: 'taxes', align: 'center' },
        { title: '状态', dataIndex: 'invoiceState', key: 'invoiceState', align: 'center' },
        {
            title: '操作',
            dataIndex: 'action',
            key: 'operation',
            width: 180,
            align: 'center',
            scopedSlots: { customRender: 'action' }
        }
        ],
      sData: {
        settlementPid: null,
      },
      listdata: [],
      pagination: {
        //分页配置
        current: 1, //当前页码 current
        pageSize: 10, //每页显示条数 pageSize
        total: 1,
        showQuickJumper: true,
        showSizeChanger: true,
        pageSizeOptions: ['1', '5', '10', '100'],
      },
      listKey: 0,
      pid: '',
      zzPid:'',
      sysSeq: 0,
      loadings: false,
      optText: '批量确认',
      selectedRowKeys: [],
      selectedRows: [],
    }
  },
  computed: {},
  mounted() {},
  methods: {
    // // 弹出模态框
    showModal(val,record) {
      this.pid = val
      this.record=record
      this.modal.modalVisible = true
      this.modal.modalTitle = '查看发票'
      this.editable=false
      this.sData.settlementPid= val
      this.getSBypid(val)
      this.getTotal()
      this.getDetailBypid(this.sData)
      
    },
    // 关闭模态详细框
    closeModal() {
      this.modal.modalVisible = false
      this.$emit('close')
    },
    closeModal2() {
      this.modal.modalVisible = false
      this.$emit('ok')
    },
    // 关闭模态详细框
    handleModalCancel() {
    },
    // 模态详细框提交按钮
    handleModalSaveOk() {
     this.getDetailBypid(this.sData)
    },
    //
    onAddData() {

    },

    // 结算确认
    async onPush() {
      this.record.settlementState='已确认'
      this.saveObjInfo(this.record)
    },
    // 保存详细信息
    async saveObjInfo(val) {
      console.log(val);
      this.btnLoading = true
      let res = await saveInfo(val)
      this.btnLoading = false
      console.log(res)
      if (res && res.code && res.code === 'C1' && res.data) {
        this.$message.success({ content: '提交成功',  duration: 2 })
        this.closeModal2()
      } else {
        this.$message.error({ content: '提交失败',  duration: 2 })
      }
    },

    // 得到销售订单消息
    async getSBypid(val) {
      let res = await getInfoByPid(val)
      if (res && res.code && res.code === 'C1') {
        this.sysSeq = res.data.sysSeq
        for (const key in res.data) {
            for (const item of this.infoDatas) {
                if(key==item.id){
                    item.value=res.data[key]
                }
            }
        }
      }
    },
    // 触发改变页码,筛选,排序时的回调
    handleTableChange(pagination, filters, sorter) {
      this.pagination.current = pagination.current
      this.pagination.pageSize = pagination.pageSize
      this.getDetailBypid(this.sData)
    },
    // 初始化页面时得到总数
    async getTotal() {
      let pages = ''
      pages = await getByConditionsCount(this.sData)
      console.log(pages)
      if (pages && pages.code && pages.code === 'C1') {
        const pagination = { ...this.pagination }
        pagination.total = pages.data
        this.pagination = pagination
        this.pagination.showTotal =  (showTotal) => {return `共 ${showTotal} 条`}
      }
    },
    //得到初始化订单商品list
    async getDetailBypid(params) {
      console.log('请求列表时传入的数据', params)
      this.loading = true
      let listdata = []
      let actionBtn =[ '查看']
      let res = ''
      res = await getByConditions(params, this.pagination)
      this.loading = false
      console.log(res)
      if (res && res.code && res.code === 'C1' && res.data) {
        const resdata = res.data
        this.orgList=res.data
         for (let item of resdata) {
            listdata.push({
               key: item.pid,
               action:actionBtn,
               ...item
               }
            )
         }
         this.listdata =listdata
      } else {
        this.listdata = []
      }
    },
    // 操作按钮
    onAction(text, record, index) {
      if (text == '查看') {
        this.$refs.viewModal.showModal(record.pid,record)
        // this.showConfirm(record)
      } else if (text == '确认') { 
        // this.showConfirm(record,'1')
        this.$refs.auditModal.editModal(record.pid, record)
      }
    },
    // 多选批量操作
    onselectChange(selectedRowKeys, selectedRows) {
      this.selectedRowKeys = selectedRowKeys
      this.selectedRows = selectedRows
      for (const item of this.selectedRows) {
        if (item.action[0] != '确认') {
          this.notAudit = true
          return
        } else {
          this.notAudit = false
        }
      }
    },
    onBatchAudit() {
      if (this.selectedRows.length) {
        if (this.notAudit) {
          this.$message.warning({ content: '已选项中含有已处理的订单，请选择未处理的订单', duration: 3 })
        } else {
          this.$refs.auditModal.batchModal(this.selectedRows)
        }
      } else {
        this.$message.warning({ content: '未选择要处理的订单', duration: 3 })
      }
    },
    onDelectData(){
      if(this.selectedRows.length){
        this.showDelConfirm(this.selectedRows)
      }else{
        this.$message.warning({ content:'未选择要删除的商品', duration: 3 })
      }
    },
    showDelConfirm(val,type) {
      let datas=[]
      if(type=='1'){
        datas[0]=val
      }else{
        datas=val
      }
      const that = this;
      this.$confirm({
        title: '是否确认删除？',
        content: '删除后不可恢复！',
        onOk() {
          let reqArr=[]
          let key='self'
          for (const item of datas) {
            reqArr.push(that.delOrder(item))
          }
          return Promise.all(reqArr).then(res => {
            console.log(res);
            for (const item of res) {
              console.log(item);
              if (item && item.code && item.code === 'C1' && item.data) {
                that.$message.success({ content:'采购订单'+item.data.saleOrderNo+ '删除成功', duration: 3 })
              } else {
                that.$message.error({ content:'采购订单'+item.data.saleOrderNo+ '删除失败，原因：'+item.message, duration: 3 })
              }
            }
            that.handleModalSaveOk()
          }).catch(err => {
            that.$message.error({ content:'操作出错:'+err, duration: 3 })
          })
        },
        onCancel() {},
      });
    },
    async delOrder(val){
      let res = await deleteInfo(val)
      return res
    },
  },
}
</script>

<style>
.recordBox {
  width: 100%;
  min-height: 80px;
}
</style>